﻿#define _CRT_SECURE_NO_WARNINGS
#include "Contact.h"
#include"SList.h"
//读取通讯录到链表中
void LoadContact(contact** con)
{
	FILE* pf = fopen("通讯录.txt","rb");
	if (pf == NULL)
	{
		perror("fopen");
		return;
	}
	PeoInfo person;
	while (fread(&person, sizeof(PeoInfo), 1, pf))
	{
		SLTPushBack(con, person);
	}
	printf("通讯录数据导入成功！！！！\n");
}
//初始化通讯录
void InitContact(contact** con)
{
	LoadContact(con);
}//实际调⽤的是链表的初始化接⼝（可以简单做⼀个头结点的初
//添加通讯录数据
void AddContact(contact** con)
{
	PeoInfo person;
	printf("请输入姓名：\n");
	scanf("%s", person.name);
	printf("请输入性别：\n");
	scanf("%s", person.sex);
	printf("请输入年龄：\n");
	scanf("%d", &person.age);
	printf("请输入联系电话：\n");
	scanf("%s", person.tel);
	printf("请输入地址：\n");
	scanf("%s", person.addr);

	SLTPushBack(con, person);
}// 链表尾插/头插
//展⽰通讯录数据
void ShowContact(contact* con) {
	printf("%-10s %-4s %-4s %15s %-20s\n", "姓名", "性别", "年龄", "联系电话", "地址");
		contact* cur = con;
	while (cur)
	{
		printf("%-10s %-4s %-4d %15s %-20s\n",
			cur->data.name,
			cur->data.sex,
			cur->data.age,
			cur->data.tel,
			cur->data.addr);
		cur = cur->next;
	}
}//链表的打印
contact* FindByName(contact* con, char name[NAME_MAX]) {
	contact* cur = con;
	while (cur)
	{
		if (strcmp(cur->data.name, name) == 0) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}
//删除通讯录数据
void DelContact(contact** con)
{
	char tem[NAME_MAX] = { 0 };
	printf("请输入你要删除的联系人姓名：\n");
	scanf("%s", tem);
	contact* ret = FindByName(*con, tem);
	if (ret == NULL)
	{
		printf("找不到该联系人删除失败！！！\n");
	}
	else
	{
		SLTErase(con, ret);
		printf("该联系人删除成功！！！\n");
	}
}//链表的删除指定位置的数据
void FindContact(contact* con)
{
	char name[NAME_MAX];
	printf("请输入你要查找的联系人姓名：\n");
	scanf("%s", name);
	contact * ret = FindByName(con, name);
	if (ret == NULL)
	{
		printf("找不到该联系人！！！\n");
	}
	else
	{
		printf("找到了该联系人！！！\n该联系人信息如下：\n");
		printf("%-10s %-4s %-4s %15s %-20s\n", "姓名", "性别", "年龄", "联系电话", "地址");
		printf("%-10s %-4s %-4d %15s %-20s\n",
			ret->data.name,
			ret->data.sex,
			ret->data.age,
			ret->data.tel,
			ret->data.addr);
	}
}
//修改通讯录数据
void ModifyContact(contact** con)
{
	char name[NAME_MAX];
	printf("请输入要修改的联系人姓名:\n");
	scanf("%s", name);
	contact* ret = FindByName(*con, name);
	if (ret == NULL)
	{
		printf("要查找的⽤⼾不存在，修改失败！\n");
		return;
	}
	printf("请输入要修改的姓名：\n");
	scanf("%s", ret->data.name);
	printf("请输入要修改的性别：\n");
	scanf("%s", ret->data.sex);
	printf("请输入要修改的年龄：\n");
	scanf("%d", &ret->data.age);
	printf("请输入要修改的联系电话：\n");
	scanf("%s", ret->data.tel);
	printf("请输入要修改的地址：\n");
	scanf("%s", ret->data.addr);
	printf("修改成功！\n");
}
// 销毁通讯录数据
void SaveContact(contact* con) {
	FILE* pf = fopen("通讯录.txt", "wb");
	if (pf == NULL) {
		perror("fopen error!\n");
		return;
	}
	//将通讯录数据写⼊⽂件
	contact* cur = con;
	while (cur)
	{
		fwrite(&(cur->data), sizeof(cur->data), 1, pf);
		cur = cur->next;
	}
	printf("通讯录数据保存成功！\n");
}
void DestroyContact(contact **con)
{
	//销毁之前把数据写入文件中
	SaveContact(*con);
	SListDesTroy(con);
}